/*
    Simple Program to find Startup applications and its paths.
    Author: @5mukx
*/

/* => Imported Dependencies
[dependencies]
widestring = "0.1.0"
winapi = { version = "-1.3.9", features = ["winuser","setupapi","dbghelp","wlanapi","winnls","wincon","fileapi","sysinfoapi", "fibersapi","debugapi","winerror", "wininet" , "winhttp" ,"synchapi","securitybaseapi","wincrypt","psapi", "tlhelp32", "heapapi","shellapi", "memoryapi", "processthreadsapi", "errhandlingapi", "winbase", "handleapi", "synchapi"] }
*/

use std::ptr::null_mut;
use winapi::um::winnt::KEY_READ;
use winapi::um::winreg::{
    HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, RegCloseKey, RegOpenKeyExW,
    RegEnumValueW,
};
use winapi::shared::minwindef::{DWORD, MAX_PATH};
use winapi::shared::ntdef::WCHAR;
use widestring::{U16CString, U16String};
use winapi::shared::minwindef::HKEY;


fn main() {
    unsafe {
        let mut hkey: HKEY = null_mut();
        let mut sub_key = U16CString::from_str("Software\\Microsoft\\Windows\\CurrentVersion\\Run").unwrap();
        
        if RegOpenKeyExW(HKEY_CURRENT_USER, sub_key.as_ptr(), 0, KEY_READ, &mut hkey) == 0 {
            list_startup_programs(hkey);
            RegCloseKey(hkey);
        }

        sub_key = U16CString::from_str("Software\\Microsoft\\Windows\\CurrentVersion\\Run").unwrap();
        if RegOpenKeyExW(HKEY_LOCAL_MACHINE, sub_key.as_ptr(), 0, KEY_READ, &mut hkey) == 0 {
            list_startup_programs(hkey);
            RegCloseKey(hkey);
        }
    }
}

fn list_startup_programs(hkey: HKEY) -> () {
    let mut index: DWORD = 0;
    let mut value_name = [0u16; MAX_PATH];
    let mut value_name_len: DWORD = MAX_PATH as DWORD;
    let mut data = [0u8; MAX_PATH];
    let mut data_len: DWORD = MAX_PATH as DWORD;
    let mut data_type: DWORD = 0;
    unsafe{
        loop {
            let result = 
                RegEnumValueW(hkey, index, value_name.as_mut_ptr(), &mut value_name_len, 
                            null_mut(), &mut data_type, data.as_mut_ptr() as *mut u8, &mut data_len);
            if result != 0 {
                break; 
            }

            let name = U16String::from_ptr(value_name.as_ptr(), value_name_len as usize);
            let value_data = U16String::from_ptr(data.as_ptr() as *const WCHAR, data_len as usize / 2);

            println!("Name: {}, Value: {}", name.to_string_lossy(), value_data.to_string_lossy());

            index += 1;
            value_name_len = MAX_PATH as DWORD;
            data_len = MAX_PATH as DWORD;
        }
    }
}
